//
//  DFComposeViewController.swift
//  FlyBlog
//
//  Created by FEI on 16/4/19.
//  Copyright © 2016年 FEI. All rights reserved.
//

import UIKit
import SVProgressHUD

class DFComposeViewController: UIViewController {

   private var maxOfLength = 25

    private var isShowPhotoSelectorView = false

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.blueColor()
        setNavigationBar()
        setupTextView()
        setupPhotoSelectorView()
        setToolBar()
        setupLengthTipLabel()
        //监听键盘frame改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("willChangeFrame:"), name: UIKeyboardWillChangeFrameNotification, object: nil)
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }

    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    @objc private func willChangeFrame(notification: NSNotification) {
        let frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue

        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue

        let y = -(UIScreen.mainScreen().bounds.height - frame.origin.y)

        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(y)
        }

        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }

    private func setupPhotoSelectorView() {
        let photoSelectorView = photoSelectorVC.view
        self.view.addSubview(photoSelectorView)
        self.addChildViewController(photoSelectorVC)

        photoSelectorView.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(UIScreen.mainScreen().bounds.height * 0.6)
            make.height.equalTo(UIScreen.mainScreen().bounds.height * 0.6)
        }

    }

    private func setupLengthTipLabel() {
        view.addSubview(lengthTipLabel)
        lengthTipLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(toolBar.snp_top).offset(-4)
            make.trailing.equalTo(toolBar).offset(-4)
        }
    }

    private func setupTextView() {
        view.addSubview(textView)
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
    }
    //设置toolBar
    private func setToolBar() {
        view.addSubview(toolBar)

        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }

        let itemSettings = [
    ["imageName":"compose_mentionbutton_background","action":"mention"],
            ["imageName":"compose_emoticonbutton_background","action":"emoticon:"],
            ["imageName":"compose_trendbutton_background","action":"trend"],
            ["imageName":"compose_toolbar_picture","action":"picture"],
            ["imageName":"compose_add_background","action":"add"],

        ]

        var items = [UIBarButtonItem]()
        var index = 0

        for dict in itemSettings {
            let imageName = dict["imageName"]!
            let action = dict["action"]!
            let item = UIBarButtonItem(imageName: imageName, target: self, action: Selector(action))
            items.append(item)

            let button = item.customView as! UIButton
            button.tag = index

            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            index++
            
        }

        items.removeLast()
        toolBar.items = items


    }
    //导航栏

    private func setNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("cancel"))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("send"))

        navigationItem.rightBarButtonItem?.enabled = false

        setNavigationBarTitle()
    }

    private func setNavigationBarTitle() {
        let prefix = "发微博"
        if let name = DFUserAccountModel.shareInstance.userAccount?.screen_name {
            let title = prefix + "\n" + name

            let titleLabel = UILabel()
            titleLabel.numberOfLines = 0
            titleLabel.textAlignment = NSTextAlignment.Center
            titleLabel.textColor = UIColor.blackColor()
            titleLabel.font = UIFont.systemFontOfSize(14)

            let attrStringM = NSMutableAttributedString(string: title)
            let range = (title as NSString).rangeOfString(name)

            attrStringM.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
            attrStringM.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)

            titleLabel.attributedText = attrStringM

            titleLabel.sizeToFit()

            navigationItem.titleView = titleLabel
        }else {
            navigationItem.title = prefix
        }

    }
//点击事件
    @objc private func picture() {
       isShowPhotoSelectorView = true
       photoSelectorVC.view.snp_updateConstraints { (make) -> Void in
        make.bottom.equalTo(self.view).offset(0)
        }

        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }

        textView.resignFirstResponder()

    }
    @objc private func trend() {
        DFPrint("#")

    }
    @objc private func mention() {
        DFPrint("@")

    }
    @objc private func emoticon(button: UIButton) {
        textView.resignFirstResponder()

        var normalImg:UIImage?
        var highlightedImg: UIImage?

        textView.inputView = textView.inputView == nil ? emotionKeyboard : nil
        if textView.inputView == nil {
            normalImg = UIImage(named: "compose_emoticonbutton_background")
            highlightedImg = UIImage(named: "compose_emoticonbutton_background_highlighted")
        }else {
            normalImg = UIImage(named: "compose_keyboardbutton_background")
            highlightedImg = UIImage(named: "compose_emoticonbutton_background_highlighted")
        }

        button.setImage(normalImg, forState: UIControlState.Normal)
        button.setImage(highlightedImg, forState: UIControlState.Highlighted)

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.textView.becomeFirstResponder()
        }

    }
    @objc private func add             () {
        DFPrint("加号")

    }

   @objc private func cancel() {

        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)

    }

   @objc private func send() {
        let text = textView.emoticonText()
    let last = maxOfLength - text.characters.count
    if last < 0 {
        SVProgressHUD.showErrorWithStatus("超出最大长度")
        return
    }

    SVProgressHUD.showWithStatus("正在发布微博..")

    let image = photoSelectorVC.photos.first

    DFStatusViewModel.shareInstance.sendStatus(text, image: image) {(error) -> () in
        if error != nil {
            SVProgressHUD.showErrorWithStatus("发布微博失败")
            return
        }

        SVProgressHUD.showErrorWithStatus("发布微博成功")

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            self.cancel()
        })

    }
    }
//MARK:懒加载
    private lazy var emotionKeyboard: HMEmoticonKeyboard = {
        let view = HMEmoticonKeyboard()

        view.textView = self.textView
        return view
    }()

    private lazy var toolBar: UIToolbar = UIToolbar()

    private lazy var textView: DFPlaceholderTextView = {
        let textView = DFPlaceholderTextView()
        textView.font = UIFont.systemFontOfSize(18)
        textView.textColor = UIColor.blackColor()
        textView.placeholder = "分享新鲜事..."
        textView.delegate = self
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return textView
    }()

    private lazy var lengthTipLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(10)
        label.textColor = UIColor.lightGrayColor()
        label.text = String(self.maxOfLength)
        label.sizeToFit()
        return label
    }()

    private lazy var photoSelectorVC: HMPhotoSelectorController = HMPhotoSelectorController()

}

extension DFComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()

        let text = textView.emoticonText()
        let last = maxOfLength - text.characters.count
        lengthTipLabel.text = String(last)
        let color = last < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
        lengthTipLabel.textColor = color
    }
}
